import React, {PureComponent, Fragment} from 'react';
import {routerRedux, Link} from 'dva/router';
import {connect} from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Radio,
  Table,
  Popconfirm,
} from 'antd';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import SearchArticleModal from './SearchArticleModal';
import Authorized from '../../utils/Authorized';
import G from '../../utils/g';
import defaultAvatar from '../../assets/admin_logo.png';

const FormItem = Form.Item;
const {Option} = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const RadioGroup = Radio.Group;
const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['关闭', '运行中', '已上线', '异常'];

@connect(({goodsList, loading}) => ({
  goodsList,
  loading: loading.models.goodsList,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    articleModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    addInputValue: '',
    checkedGroupList: [],
    selectedArticle:{},
  };

  componentDidMount() {
    const {dispatch, location} = this.props;
    this.id = G.getUrlValue('id', location.search);
    dispatch({
      type: 'goodsList/fetchBindArticleList',
      payload: {
        goodsId: this.id
      }
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {dispatch} = this.props;
    const {formValues} = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = {...obj};
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      startIndex: (pagination.current - 1) * pagination.pageSize, //此处峻吉分页需要是第一项的序号，如第二页传10，而不是具体的分页码1，2，3
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'businessList/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const {form, dispatch} = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'businessList/fetch',
      payload: {},
    });
  };

  toggleForm = () => {
    this.setState({
      expandForm: !this.state.expandForm,
    });
  };

  handleMenuClick = e => {
    const {dispatch} = this.props;
    const {selectedRows} = this.state;

    if (!selectedRows) return;

    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'businessList/remove',
          payload: {
            no: selectedRows.map(row => row.no).join(','),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const {dispatch, form} = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'businessList/fetch',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
    this.props.form.resetFields();
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleArticleModalVisible = flag => {
    this.setState({
      articleModalVisible: !!flag,
    });
  };

  handleAdd = fields => {
    this.props.dispatch({
      type: 'businessList/add',
      payload: {
        description: fields.desc,
      },
    });

    message.success('添加成功');
    this.setState({
      modalVisible: false,
    });
  };

  bindChangeStatus = (id, action)=> {
    const {dispatch} = this.props;
    dispatch({
      type: 'businessList/changeStatus',
      payload: {
        user_id: id,
        action: action
      }
    });
  }

  bindChangeBind = (id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'goodsList/fetchUnbindArticle',
      payload: {
        goodsId: this.id,
        articleId: id,
      }
    }).then(res=>{
      console.log(res);
    })
  }

  okHandle = () => {
    const { dispatch, form, goodsList: {bindArticleGoods} } = this.props;
    const {selectedArticle} = this.state;
    const { name, imgs=[],id, min_price } = bindArticleGoods;

    form.validateFields((err, fieldsValue) => {
      if (err) {
        return
      };
      if(!selectedArticle.id){
        message.error('请选择要绑定的文章');
        return false;
      }
      form.resetFields();
      dispatch({
        type: 'goodsList/bindArticle',
        payload: {
          ...fieldsValue,
          goodsId: id,
          goodsName: name,
          goodsCover: imgs[0],
          goodsPrice: min_price,
          articleId: selectedArticle.id
        }
      }).then(()=>{
        dispatch({
          type: 'goodsList/saveBindArticle',
          payload: selectedArticle
        });
        message.success('添加成功');
        this.setState({
          modalVisible: false,
        });

      })
    });
  }

  handleArticleModalOk = () =>{

  }

  handleSelectArticle=(article)=>{
    // const { dispatch } = this.props;
    this.setState({
      selectedArticle: article,
      articleModalVisible: false,
    });
  }

  render() {
    console.log(this.props);
    const {goodsList: {bindArticleList, bindArticleGoods}, loading, form} = this.props;
    const {selectedRows, modalVisible, articleModalVisible, selectedArticle} = this.state;


    const columns = [
      {
        title: '图片',
        render: (val, record)=> {
          return <img src={record.cover} width="100" height={60}/>
        }
      },
      {
        title: '标题',
        dataIndex: 'title',
      },
      {
        title: '描述',
        dataIndex: 'summary',
      },
      {
        title: '作者',
        dataIndex: 'authorName',
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            <Popconfirm title="你确定要取消绑定此文章？" okText="确定" cancelText="取消" onConfirm={()=> {
              this.bindChangeBind(record.id)
            }}>
              <a href="javascript:;">取消绑定</a>
            </Popconfirm>
          </Fragment>
        ),
      },
    ];

    const { name='', desc='', imgs= [] } = bindArticleGoods;

    const description = (<div>
        <img src={imgs[0]} width="60" height="60" style={{float:'left', marginRight:12}} />
        <h4>{name}</h4>
        <p>{desc}</p>
    </div>);

    return (
      <PageHeaderLayout
        title="商品相关文章管理"
        content={description}
      >
        <Card bordered={false}>
          <div>
            <div>
              <Button icon="plus" type="primary" onClick={this.handleModalVisible}>
                绑定文章
              </Button>
            </div>
            <Table
              style={{marginTop:24}}
              loading={loading}
              rowKey={(record)=>`article${record.id}`}
              dataSource={bindArticleList}
              columns={columns}
              pagination={false}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <Modal
          title="绑定文章"
          visible={modalVisible}
          onOk={this.okHandle}
          onCancel={() => this.handleModalVisible()}
        >
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="选择文章">
            {form.getFieldDecorator('article', {
            })(<Button onClick={this.handleArticleModalVisible}>请选择</Button>)}
            <p><img src={selectedArticle.cover} width="100%" />{selectedArticle.title}</p>
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="X轴">
            {form.getFieldDecorator('x', {
              rules: [{ required: true, message: '请输入X轴位置，默认0.5' }],
              initialValue: '0.5',
            })(<Input placeholder="请输入显示X轴的位置，0-1之间的小数" />)}
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="Y轴">
            {form.getFieldDecorator('y', {
              rules: [{ required: true, message: '请输入Y轴位置，默认0.5' }],
              initialValue: '0.5',
            })(<Input placeholder="请输入显示Y轴的位置，0-1之间的小数" />)}
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="标签位置">
            {form.getFieldDecorator('left', {
              rules: [{ required: true, message: '请输入Y轴位置，默认0.5' }],
              initialValue: 1,
            })(
              <RadioGroup>
                <Radio value={1}>左侧</Radio>
                <Radio value={0}>右侧</Radio>
              </RadioGroup>
            )}
          </FormItem>
        </Modal>
        <SearchArticleModal
          handleHide={this.handleArticleModalVisible}
          handleOk={this.handleArticleModalOk}
          modalVisible={articleModalVisible}
          selectedRows={[]}
          onSelect = {this.handleSelectArticle}
        />
      </PageHeaderLayout>
    );
  }
}
